package zhanglu.family.socket.demo.busdemo.client2;

import net.sf.json.JSONObject;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import zhanglu.family.socket.bean.busbean.BusHeadBean;
import zhanglu.family.socket.bean.busbean.BusMsgBean;
import zhanglu.family.socket.demo.busdemo.response.ResponseTest;
import zhanglu.family.socket.textline.busclient.BusTCPClient;

public class ClientHandlerDemo2 extends IoHandlerAdapter {

    private BusTCPClient client;

    public ClientHandlerDemo2(BusTCPClient client) {
        this.client = client;
    }

    /**
     * messageReceived:当接收了一个消息时调用,这个也是最重要的
     */
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {

        System.out.println(message);

        JSONObject json = JSONObject.fromObject(message);
        BusMsgBean msg = (BusMsgBean) JSONObject.toBean(json, BusMsgBean.class);

        BusHeadBean head = msg.getHead();

        ResponseTest mess = new ResponseTest();

        mess.setResponse("消息我收到了啊");

        client.post(head.getHeadId(), head.getSeqId(), head.getSessionSequence(), mess);
    }

    /**
     * sessionClosed:当连接关闭时调用
     */
    @Override
    public void sessionClosed(IoSession session) throws Exception {

        System.out.println("断开");
        super.sessionClosed(session);

        client.reconnection();
    }

    /**
     * exceptionCaught:当实现IoHandler的类抛出异常时调用
     */
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {

        System.out.println("断开异常");
        client.reconnection();

    }
}
